<template>
    <view class="container">
        <myNavigation ref="navBar"></myNavigation>



        <!-- 轮播图 -->
        <view class="opus_imgs">
            <swiper :current="current" duration="500" interval="5000" :autoplay="false" :onChange="handleSwiperChange">
                <block v-for="(item, index) in opusInfo.imgSrc" :key="index">
                    <swiper-item>
                        <image :src="item" class="slide-image" mode="aspectFill" />
                    </swiper-item>
                </block>
            </swiper>
            <!--  -->
            <view class="custom-pagination" v-if='opusInfo.imgSrc.length > 1'>
                <block v-for="(     item, index     ) in      opusInfo.imgSrc     " :key="index">
                    <view class="pagination-bullet" :class="{ active: current === index }" :data-index="index"
                        @tap="onPaginationTap">
                    </view>
                </block>
            </view>
        </view>

        <!-- 标题 -->
        <view class="opus_title">{{ opusInfo.des }}</view>

        <!-- 标签 -->
        <view class="opus_tags">
            <block v-for="(item, index) in opusInfo.tags">
                <view class="tags_item">
                    {{ item }}
                </view>
            </block>
        </view>


        <!-- 作者信息 -->
        <view class="author_info">
            <view class="info_l" @tap="toUserInfoPage">
                <view class="profile_photo">
                    <image :src="opusInfo.profilePhoto" mode="aspectFill" />
                </view>
                <view class="name_date">
                    <view class="author_name">{{ opusInfo.authorName }}</view>
                    <view class="author_date">{{ opusInfo.date }}发布</view>
                </view>
            </view>
            <view class="info_r" @tap="follow" v-if="userId !== curUserId">
                <view class="follow " :class="{ isFollow: opusInfo.isFollow }">
                    {{ opusInfo.isFollow ? "已关注" : " 关注" }}
                </view>
            </view>
            <view class="info_r" @tap="openModel" v-if="userId === curUserId">
                <view class="iconfont icon">&#xe667;</view>
            </view>
        </view>

        <!-- 点赞展示 -->
        <view class="liking_show" v-if="+opusInfo.likes !==0">
            <view class="profile_photos">
                <block v-for='(item, index) in opusInfo.likesPhotoList' :key="index">
                    <view class="photo_item">
                        <image :src="item" mode="aspectFill" />
                    </view>
                </block>
            </view>
            <view class="">{{ opusInfo.likes }}人已赞</view>
        </view>

        <!-- 菜谱来源 -->
        <view class="menu_source_box" v-if="recipeId !== 'null'">
            <view class="menu_source_h">做同款</view>
            <view class="menu_source_body" @tap=toMenuInfoPage>
                <view class="menu_img">
                    <image :src="menuInfo.imgSrc" mode="aspectFill" />
                </view>
                <view class="menu_info">

                    <view class="title">{{ menuInfo.title }}</view>

                    <view class="tag" v-if="menuInfo.tags">
                        {{menuInfo.tags}}
                    </view>

                    <view class=" menu_data">

                        <text class="grade" v-if="menuInfo.garde !== ''">{{ menuInfo.grade }}分</text>
                        <!-- {{ f_item.number }} -->
                        <text class="number" v-if="menuInfo.favoritesNum">{{ menuInfo.favoritesNum }}人收藏</text>
                    </view>
                    <!-- {{ f_item.author }} -->
                    <view class="author_name">{{menuInfo.authorName}}</view>
                </view>
            </view>
        </view>

        <!--   底部导航栏 -->
        <view class="nav_bottom iconfont ">
            <view class="nav_item share" @tap="share">
                <view class="icon"> &#xe602;</view>
                <view class="">分享给好友</view>
            </view>
            <view class="nav_item liking" @tap="liking">

                <view class="icon" :class="{ active: opusInfo.isLiking }">{{ opusInfo.isLiking
                    ?
                    "&#xe61d;"
                    :
                    "&#xe61c;" }} </view>
                <view class="">{{ opusInfo.isLiking ? "已赞" : "点赞" }}</view>
            </view>
        </view>

        <!-- 删除作品 -->
        <view class="setting_model" :class="{hide: !isSetting}">
            <view class="setting_content " :class="{hide: !isSetting}">
                <view class="setting_choose">
                    <view class="setting_btn" @tap.stop="removeOpus">删除作品</view>
                </view>
                <view class="close_model" @tap.stop="closeModel">取消</view>
            </view>
        </view>
        <view class="box"></view>
    </view>
</template>

<script setup>
    import './opusInfo.scss'
    import { ref, onMounted, reactive, inject } from 'vue';
    import Taro, { useRouter } from "@tarojs/taro";
    import myNavigation from '../../../components/myNavigation.vue';

    // 注入配置
    const config = inject('config');
    const baseUrl = config.baseUrl; // 从全局配置中读取 baseUrl


    // 切换轮播图
    const current = ref(0);
    const handleSwiperChange = (e) => {
        current.value = e.detail.current;
    };
    const onPaginationTap = (event) => {
        const index = event.target.dataset.index;
        if (index !== undefined) {
            current.value = parseInt(index, 10);
        }
    };



    // 作品信息


    const opusInfo = ref({
        // 轮播图图片信息
        imgSrc: [],
        isFollow: "",
        tags: ['好吃爱吃', '真的太好吃啦', '真的太好吃啦', '真的太好吃啦', '真的太好吃啦', '真的太好吃啦'],
        likesPhotoList: [],
        likes: 0
    });




    // 菜谱信息
    const menuInfo = ref({});





    // 关注作者点击事件

    const follow = () => {
        if (opusInfo.value.isFollow) {
            // 取消关注
            Taro.request({
                url: `${baseUrl}/follow/removeFollow?followerId=${curUserId}&followedId=${userId}`,
                method: 'DELETE',
                header: {
                    'content-type': 'application/json' // 默认值
                },
            })

        } else {
            // 
            Taro.request({
                url: `${baseUrl}/follow/addFollow?followerId=${curUserId}&followedId=${userId}`,
                method: 'POST',
                header: {
                    'content-type': 'application/json' // 默认值
                },
            })
        }
        opusInfo.value.isFollow = !opusInfo.value.isFollow;
    }


    // 跳转菜谱详细页面
    const toMenuInfoPage = () => {
        Taro.navigateTo({
            // 连接数据库可以通过传递id值来方便后续查询菜谱信息
            url: `../menuInfo/menuInfo?recipeId=${recipeId}&userId=${curUserId}`
        });
    }

    // 跳转到用户信息界面
    const toUserInfoPage = () => {
        console.log(userId, curUserId);
        Taro.navigateTo({
            url: `../userInfo/userInfo?userId=${userId}&curUserId=${curUserId}`
        });
    }



    // 点赞点击事件
    const liking = () => {
        if (opusInfo.value.isLiking) {

            // 取消点赞
            Taro.request({
                url: `${baseUrl}/likes/removeLikes?userId=${curUserId}&opusId=${opusId}`,
                method: 'DELETE',
                header: {
                    'content-type': 'application/json' // 默认值
                },
                success: (res) => {
                    opusInfo.value.likes = +opusInfo.value.likes - 1;
                    Taro.request({
                        url: `${baseUrl}/opus/getPhotoList?opusId=${opusId}`,
                        success: (res) => {
                            opusInfo.value.likesPhotoList = res.data.data
                        }
                    })
                }
            })
        } else {

            // 获取当前用户的信息(头像),只显示五个头像,超过五个删除最后一个头像
            // 需要实时显示:当点赞时根据时间排序显示前五个最新的用户头像信息,然后显示到页面上,
            //删除则需要删除点赞列表中这个用户的信息, 然后再查询显示,而不是直接对当前的数据操

            // 点赞
            Taro.request({
                url: `${baseUrl}/likes/addLikes?userId=${curUserId}&opusId=${opusId}`,
                method: 'POST',
                success: (res) => {
                    opusInfo.value.likes = +opusInfo.value.likes + 1;
                    Taro.request({
                        url: `${baseUrl}/opus/getPhotoList?opusId=${opusId}`,
                        success: (res) => {
                            opusInfo.value.likesPhotoList = res.data.data
                        }
                    })
                }
            })
        }
        opusInfo.value.isLiking = !opusInfo.value.isLiking;

    }


    // 删除作品按钮显示
    const isSetting = ref(false)
    const openModel = () => {
        isSetting.value = true;
    }
    const closeModel = () => {
        isSetting.value = false;
    }


    // 删除作品
    const removeOpus = () => {
        Taro.request({
            url: `${baseUrl}/opus/deleteOpus?opusId=${opusId}`,
            method: "DELETE",
            header: {
                'content-type': 'application/json' // 默认值
            },
            success: (res) => {
                if (res.data.message === "success") {
                    showSuccess(res.data.data);
                } else {
                    showError(res.data.data)
                }
            }
        })
    }
    // 函数：删除成功后返回上一页：
    function showSuccess(msg) {
        const curTime = ref(2);
        Taro.showToast({
            title: `${msg}`,
            icon: 'success',
            mask: true,
            duration: 1000,
            complete: () => {
                const intervalId = setInterval(() => {
                    curTime.value -= 1;
                    if (curTime.value > 0) {
                        Taro.showToast({
                            title: `${msg},${curTime.value}s后返回上一页`,
                            icon: 'none',
                            mask: true,
                            duration: 1000 // 每次显示1秒
                        });
                    } else {
                        clearInterval(intervalId); // 清除定时器
                        // 执行跳转操作
                        Taro.navigateBack({
                            delta: 1
                        });
                    }
                }, 1000);
            }
        });
    }
    // 函数:失败显示
    function showError(msg) {
        Taro.showToast({
            title: `${msg}`,
            icon: 'error',
            duration: 2000, // 持续时间为2s
        });
    }




    // 导航栏信息
    const navBar = ref(null);

    const navigationHome = () => {
        Taro.switchTab({
            url: '../../../pages/index/index',
        });
    };

    const setNavBar = () => {
        if (navBar.value) {
            navBar.value.navigationHome = navigationHome;
            navBar.value.navigationTitle = "作品详细";
        }
    }



    // // 实际菜谱信息需要从外部值传递进来
    // const menu_info = JSON.parse(decodeURIComponent(router.params.menuInfo))

    const getRecipeData = () => {

        if (recipeId === "null") return;
        Taro.request({
            url: `${baseUrl}/recipe/getRecipeInfo?recipeId=${recipeId}`,
            header: {
                'content-type': 'application/json' // 默认值
            },
            success: function (res) {
                console.log(11);
                menuInfo.value = res.data.data;
                console.log(res.data.data);
                menuInfo.value.tags = res.data.data.tags ? JSON.parse(res.data.data.tags).join("、") : "";


            }
        })
    }
    const getOpusData = () => {
        Taro.request({
            url: `${baseUrl}/opus/getOpusInfo?userId=${curUserId}&opusId=${opusId}`,
            header: {
                'content-type': 'application/json' // 默认值
            },
            success: function (res) {
                console.log(res.data.data);
                opusInfo.value = res.data.data;
                opusInfo.value.imgSrc = JSON.parse(opusInfo.value.imgSrc)
                console.log(typeof (opusInfo.value.imgSrc.length));
                opusInfo.value.tags = JSON.parse(opusInfo.value.tags)
                console.log(opusInfo.value);


            }
        })
    }

    // curUserId为当前登录用户的id
    const router = useRouter();
    const { opusId, userId, recipeId, curUserId } = router.params;
    // const opusInfo.value = JSON.parse(router.params.opusInfo.value);

    onMounted(() => {
        getOpusData();
        getRecipeData();
        setNavBar();
    });
</script>